import React, { Component } from 'react';
import { Row, Col, Form, Button, Icon } from 'antd';
import { IconFont } from '../IconFont';
import engine from '../../utils/engine';
import './index.less';

const DEFAULT_HEIGHT = 44;
const easing = (t) => Math.sin((t * Math.PI) / 2);

class SearchBar extends Component {
  state = {
    isExpand: false,
    needExpand: false,
  };
  searchRef = null;
  tid = 0;
  // 响应式配置
  responsive = {
    xs: 12,
    sm: 8,
    md: 8,
    lg: 6,
    xl: 6,
    xxl: 4,
  };

  resize = () => {
    clearTimeout(this.tid);
    this.tid = setTimeout(() => {
      const height = this.computeHeight();
      if (this.isExpand) {
        this.searchRef.style.height = height + 'px';
      }
    }, 100);
  };

  componentDidMount() {
    const { createForm } = this.props;
    createForm && createForm(this.form);

    window.addEventListener('resize', this.resize);
    setTimeout(() => {
      this.computeHeight();
    });
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.resize);
  }

  getColResponsive = (colspan = 1) => {
    const obj = {};
    for (const [key, val] of Object.entries(this.responsive)) {
      obj[key] = val * colspan;
    }
    return obj;
  };

  // 计算高度
  computeHeight() {
    const el = this.searchRef;
    el.style.height = 'auto';
    // fit margin
    const height = el.clientHeight;
    el.__height__ = height;
    this.setState({
      needExpand: height > DEFAULT_HEIGHT,
    });
    el.style.height = '';
    return height;
  }

  // 动画transition组件不方便控制，用JS代替
  toggleExpand = () => {
    const { isExpand } = this.state;
    const el = this.searchRef;
    if (isExpand) {
      const { __height__ } = el;
      __height__ &&
        engine(
          200,
          (p) => {
            el.style.height = __height__ - (__height__ - DEFAULT_HEIGHT) * p + 'px';
          },
          easing
        ).then(() => {
          this.setState({ isExpand: false });
        });
    } else {
      const height = this.computeHeight();
      engine(
        200,
        (p) => {
          el.style.height = DEFAULT_HEIGHT + (height - DEFAULT_HEIGHT) * p + 'px';
        },
        easing
      ).then(() => {
        this.setState({ isExpand: true });
      });
    }
  };

  handleReset = () => {
    this.props.form.resetFields();
    this.props.reset && this.props.reset();
  };

  handleSearch = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const params = {};
        Object.keys(values).forEach((key) => {
          if (values[key] !== undefined && values[key] !== '') {
            params[key] = values[key];
          }
        });
        this.props.onChange && this.props.onChange(params);
      }
    });
  };

  render() {
    const { isExpand, needExpand } = this.state;
    const { className, searchList, form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <div className={`searchbar ${className}`}>
        <div className='searchbar-form' ref={(ref) => (this.searchRef = ref)}>
          <Form autoComplete='off'>
            <Row>
              <Col {...this.responsive} className='searchbar-form-operate'>
                <div className='searchbar-form-item'>
                  <Button className='mr-10' icon={'redo'} onClick={this.handleReset}>
                    重置
                  </Button>
                  <Button type='primary' icon={'filter'} onClick={this.handleSearch}>
                    查询
                  </Button>
                  {needExpand && (
                    <Button type='link' onClick={this.toggleExpand} className='ml-10'>
                      {isExpand ? '收起' : '展开'}
                      <Icon
                        type='right'
                        style={{
                          transform: `rotate(${isExpand ? 270 : 90}deg)`,
                          display: 'inline-block',
                          color: '#1890ff',
                        }}
                      />
                    </Button>
                  )}
                </div>
              </Col>
              {searchList.map((item) => (
                <Col key={item.name} {...this.getColResponsive(item.colspan)}>
                  <div className='searchbar-form-item'>
                    <Form.Item>{getFieldDecorator(item.name, { ...item.options })(item.component)}</Form.Item>
                  </div>
                </Col>
              ))}
            </Row>
          </Form>
        </div>
      </div>
    );
  }
}

export default Form.create()(SearchBar);
